package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"

	"github.com/KevinGong2013/wechat"
	MQTT "github.com/eclipse/paho.mqtt.golang"
	"gopkg.in/vmihailenco/msgpack.v2"
	//"mtype"
	"flag"
)

func StartBot(c chan int) (*wechat.WeChat, error) {
	bot, err := wechat.AwakenNewBot(nil)
	if err != nil {
		panic(err)
	}

	bot.Handle(`/login`, func(arg2 wechat.Event) {
		isSuccess := arg2.Data.(int) == 1
		if isSuccess {
			fmt.Println(`login Success`)
			c <- 1
		} else {
			fmt.Println(`login Failed`)
		}
	})
	bot.Handle(`/msg/solo`, func(evt wechat.Event) {
		data := evt.Data.(wechat.EventMsgData)
		if data.IsMediaMsg {
			if path, err := bot.DownloadMedia(data.MediaURL, data.OriginalMsg[`MsgId`].(string)); err == nil {
				print(path)
				//x.bot.SendFile(path, to)
			}
		}
		fmt.Println(`/msg/solo/` + data.Content)
	})
	return bot, nil
}
func RecvMsgSend(bot *wechat.WeChat, msg MQTT.Message, to string) {
	//print("recv ok\n")
	paybuff := msg.Payload()
	//var v CamEvent
	var dst interface{}
	err := msgpack.Unmarshal(paybuff, &dst)
	if err != nil {
		//print(v.e)
	}
	ol := dst.([]interface{})
	evstr := ol[2].(string)
	imgbuff := ol[3].(string)
	data2 := []byte(imgbuff)
	//print(imgbuff)
	ilen := len(data2)
	finfo := wechat.MType{
		IName: "hello.png",
		ISize: int64(ilen)}
	contacts, _ := bot.ContactsByNickName(to)
	toName := contacts[0].UserName
	go bot.SendTextMsg(evstr, toName)
	go bot.SendFileEx(data2, finfo, toName)
}
func init() {
	//	bytes, err := ioutil.ReadFile(filename)
}

func main() {
	confpath := flag.String("conf", "conf.json", "ex -conf conf.json")
	flag.Parse()
	data, _ := ioutil.ReadFile(*confpath)
	var config = map[string]string{}
	if err := json.Unmarshal(data, &config); err != nil {
		fmt.Println("Unmarshal: ", err.Error())
		return
	}
	c := make(chan int)
	bot, _ := StartBot(c)
	go bot.Go()
	blogin := <-c
	if blogin == 1 {
		print("login")
	}

	//*/
	opts := MQTT.NewClientOptions()
	opts.AddBroker(config["mqurl"])
	//opts.SetClientID(*id)
	opts.SetUsername(config["user"])
	opts.SetPassword(config["passwd"])
	//MessageHandler
	to := config["to"]
	opts.OnConnect = func(client MQTT.Client) {
		print("onconnect ok")
		client.Subscribe(config["suburl"], 1, func(client MQTT.Client, msg MQTT.Message) {
			//msg.Payload
			RecvMsgSend(bot, msg, to)
		})
	}
	client := MQTT.NewClient(opts)
	//client.Connect()
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	bexit := <-c
	if bexit == 1 {
		print("exit")
	}
}
